package com.baizhi.interceptors;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baizhi.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
//        response.addHeader("Access-Control-Allow-Origin","*");
        //获取请求头中令牌
        String token = request.getHeader("access-token");
        try {
            JWTUtils.verify(token);//验证令牌
            return true;//放行请求
//        } catch (SignatureVerificationException e) {
//            e.printStackTrace();
//            map.put("msg","无效签名!");

        } catch (TokenExpiredException e) {
////        }catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token过期!");
        }
//            throw new BusinessException(ResponseEnum.TokenExpiredException);
////            return R.setResult(ResponseEnum.TokenExpiredException);
//        }
//        catch (NullPointerException e) {
//            throw new BusinessException(ResponseEnum.NullPointer);
//
//        }

//        }catch (AlgorithmMismatchException e){
//            e.printStackTrace();
//            map.put("msg","token算法不一致!");

        catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效!!");
//            throw new BusinessException(ResponseEnum.INVALID_TOKEN);
        }
//        map.put("state",false);//设置状态
        //将map 专为json  jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);

        return false;
    }

//        return false;




}
